import Vue from "vue";
import Router from "vue-router";
import Login from "@/pages/login";
import store from "../store";

Vue.use(Router);

const hidden = true;

export const constantRoutes = [
  {
    path: "/login",
    name: "登录",
    component: Login,
    meta: {
      hidden,
      title: "登录"
    }
  },
  {
    path: "/",
    name: "/home",
    redirect: "/home",
    meta: {
      hidden
    }
  }
];

export const asyncRoutes = [
  {
    path: "/home",
    name: "home",
    redirect: "/admin",
    meta: {
      roles: ["admin"],
      hidden
    }
  },
  {
    path: "/admin",
    name: "Admin",
    redirect: "/admin/users",
    component: () => import("@/layout/admin"),
    meta: {
      title: "后台管理",
      roles: ["admin"]
    },
    children: [
      {
        path: "/admin/users",
        name: "users",
        component: () => import("@/pages/admin/users"),
        meta: {
          title: "用户管理",
          roles: ["admin"]
        }
      }
    ]
  },
  {
    path: "/home",
    name: "home",
    component: () => import("@/pages/home/index"),
    meta: {
      title: "云盘首页",
      roles: ["user"]
    }
  },
  {
    path: "*",
    redirect: "/",
    meta: {
      hidden
    }
  }
];

const createRouter = () =>
  new Router({
    // mode: 'history', // require service support
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  });

const router = createRouter();

const whiteList = ["/login"];

router.beforeEach(async (to, from, next) => {
  // 设置网页标题
  document.title = "超奇的云盘";

  // 拿到本地的 token
  const token = localStorage.getItem("I-Token");

  let user = store.getters.user;

  // 如果有存储 token
  if (token) {
    if (user && user.role) {
      next();
    } else {
      // 判断是否去 login 页面
      if (to.path === "/login") {
        next("/");
      } else {
        try {
          let user = await store.dispatch("user/getInfo");

          let roleList = ["admin", "user"];
          // 有返回值
          if (user && roleList.includes(user.role)) {
            // 进行路由筛选
            const accessRoutes = await store.dispatch(
              "permission/generateRoutes",
              [user.role]
            );
            // 添加路由
            router.addRoutes(accessRoutes);
            // 继续
            next({ ...to, replace: true });
          } else {
            // 否则登出
            store.dispatch("user/logout");
            next("/login");
          }
        } catch (error) {
          console.log(error);

          store.dispatch("user/logout");
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next("/login");
    }
  }
});

export default router;
